<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\Banner;
use app\common\model\card\Entitylog;
use app\common\model\card\Kabaw;
use app\common\model\card\Kabawlogtype;
use app\common\model\card\Kabawtype;
use app\common\model\card\Type;
use app\common\model\Machine;
use app\common\model\Member;
use app\common\model\Merchantgoods;
use app\common\model\Mycard;
use app\common\model\Mycardlog;
use app\common\model\Order;
use app\common\model\Question;
use app\common\model\Tutorial;
use Exception;
use fast\Http;
use think\Db;
use think\Log;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 处理洗车类型名称
     * */
    public function handleCardType()
    {
        if(empty($this->request->param("id"))) $this->error("id为空");
        if(empty($this->request->param("name"))) $this->error("name为空");//人工标准洗车（含内饰）
        $card_type_id=$this->request->param("id");
        $name=$this->request->param("name");
        Db::startTrans();
        try {
            Type::where(["id"=>$card_type_id])->update(["name"=>$name]);
            Kabawlogtype::where(["card_type_id"=>$card_type_id])->update(["card_type_name"=>$name]);
            Kabawtype::where(["card_type_id"=>$card_type_id])->update(["card_type_name"=>$name]);
            Mycardlog::where(["card_type_id"=>$card_type_id])->update(["card_type_name"=>$name]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("成功");
    }
    /**
     * 处理之前的实体卡兑换码
     * */
    public function handleNumber()
    {
        $model= new Entitylog();
        $code_log =$model->all();
        $update=[];
        if (!empty($code_log)) {
            foreach ($code_log as $k=>$v){
                $update[$k]=[
                    "id"=>$v["id"],
                    "exchange_number"=>"000".$v["exchange_number"],
                ];
            }
            if(!empty($update)){
                $model->saveAll($update);
            }
        }

    }


    /**
     * 首页
     *
     */
    public function index()
    {
        $model = new Order();
        $order=Order::get(256);
        $member=Member::find($order["member_id"]);
        //$member["wxopenid"]="onyHr51gVC3cRH8BqCBjp8Eb8JR8";
        if(!empty($member["wxopenid"])){
            if($order["type_data"]==1 || $order["type_data"]==2){
                $template_id="T2l7vsvGSY6a-3hMs2zVAbRCnsUP0_pAVlqPav0P6gw";
                //卡包
                $data=[
                    "thing3"=>[
                        "value"=>$order["name"],
                    ],
                    "amount4"=>[
                        "value"=>$order["price"],
                    ],
                    "time5"=>[
                        "value"=>date("Y-m-d H:i:s",time())
                    ],
                ];
                $mycard=Mycard::field("start_time,end_time")->where(["order_id"=>$order["id"]])->find();
                if(!empty($mycard)){
                    $data["time5"]=[
                        "value"=>date("Y-m-d H:i:s",$mycard["start_time"])."~".date("Y-m-d H:i:s",$mycard["end_time"])
                    ];
                }
            }
            if(empty($order["type_data"])){
                $template_id="nKrtffukSy1Ov9SBf1HbF-81XvqiDkLoQYRXme3OFjY";
                $data=[
                    "character_string2"=>[
                        "value"=>$order["order_no"],
                    ],//订单编号
                    "amount3"=>[
                        "value"=>$order["price"],
                    ],//订单金额
                    "thing5"=>[
                        "value"=>$merchant["name"]??'',
                    ],//商户名称
                    "thing8"=>[
                        "value"=>$order["name"]
                    ],//产品名称
                    "time4"=>[
                        "value"=>date("Y-m-d H:i:s",time())
                    ],//支付时间
                ];
            }
            //$order["id"]=286;
            $this->send_temp($template_id,$member["wxopenid"],$data,"my_pages/orderDetails/orderDetails?id=".$order["id"]);
        }
        /*$model = new Order();
        $order=Order::get(207);
        $res=$model->calculateCommission($order);
        die();*/
        die();
        //生成机器二维码
        $list=Machine::all();
        $model=new Machine();
        if(!empty($list)){
            foreach ($list as $v){
                $code=$model->createWxCode($v["machineID"],'release');
            }
        }
        die();
        $model=new Order();
        $order = Order::get(203);
        $res=$model->agentCommission($order);
        die();
        $order = Order::get(64);
        $info = "您已在平台" . date("Y-m-d H:i:s") . " 购买" . $order["name"] . " ，价格" . $order["actual_payment"] . "元。祝你行程愉快。";
        \app\common\model\Message::create([
            "title" => "核销成功",
            "member_ids" => $order["member_id"],
            "info" => $info,
            "createtime" => time(),
        ]);
        die();
        $time = time();
        $mycardModel = new Mycard();
        if ($order["type_data"] > 0) {
            $mycardlogModel = new Mycardlog();
            $card_data = [
                "order_id" => $order["id"],
                "card_kabaw_id" => $order["card_kabaw_id"] ?? 0,
                "name" => $order["name"],
                "price" => $order["price"],
                "illustrate" => $order["illustrate"],
                "details" => $order["details"],
                "member_id" => $order["member_id"],
                "type_data" => $order["type_data"],
                "write_number" => $mycardlogModel->write_number(10),
                "createtime" => $time
            ];
            $cardlog_data = [];
            $write_number = $mycardlogModel->write_number(10);
            if ($order["type_data"] == 1) {
                //卡包
                $kabaw = Kabaw::get($order["card_kabaw_id"]);
                $time = time();
                if (!empty($kabaw)) {
                    $card_data["start_time"] = $time;
                    $card_data["end_time"] = strtotime("+" . $kabaw["fate"] . " days", $time);
                    $kabawtype = Kabawtype::where(["card_kabaw_id" => $kabaw["id"]])->select();//卡包洗车类型
                    if (!empty($kabawtype)) {
                        foreach ($kabawtype as $k => $v) {
                            $cardlog_data[$k] = [
                                "card_type_name" => $v["card_type_name"],
                                "card_type_id" => $v["card_type_id"],
                                "number" => $v["number"],
                                "residue" => $v["number"],
                                "price" => $v["price"],
                                "all_cost" => $v["all_cost"],
                                "write_number" => $write_number,
                            ];
                        }
                    }
                }
            }
            if (!empty($card_data)) {
                $mycard_id = $mycardModel->insertGetId($card_data);
                $mycardModel->getCode($mycard_id, $order["type_data"]);//生成二维码
                if (!empty($cardlog_data)) {
                    foreach ($cardlog_data as &$v) {
                        $v["mycard_id"] = $mycard_id;
                    }
                    $mycardlogModel->allowField(true)->saveAll($cardlog_data);
                }
            }
        } else {
            //普通商品
            $orderModel = new Order();
            //普通商品生成核销码
            $order_data["write_number"] = $orderModel->write_number(6);
            $mycardModel->getCode($order["id"], 0);//生成二维码
        }
        if (in_array($order["type_data"], [0, 2])) {
            $model = new Order();
            $model->calculateCommission($order);
        }
        $this->success('请求成功');
    }

    /**
     * 获取平台所有洗车类型
     * */
    public function cardType()
    {
        $list = Type::field("id,name,price")->where(["switch" => '1'])->select();
        $this->success("成功", $list);
    }

    /**
     * 获取商家端配置
     * */
    public function merchantConfig()
    {
        $list["merchant_text"] = \think\Config::get('site.merchant_text');
        $list["merchant_tip"] = \think\Config::get('site.merchant_tip');
        $list["merchant_tallTip"] = \think\Config::get('site.merchant_tallTip');
        $this->success("成功", $list);
    }

    /**
     * 获取配置
     * */
    public function getConfig()
    {
        $list["platformMobile"] = \think\Config::get('site.platformMobile');
        $list["commission"] = \think\Config::get('site.commission');
        $list["highest_money"] = \think\Config::get('site.highest_money');
        $list["minimum_money"] = \think\Config::get('site.minimum_money');
        $this->success("成功", $list);

    }

    /**
     * 教程列表
     * */
    public function tutorialList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Tutorial::paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);

    }

    /**
     * 支付回调
     * @param $data
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $type_data = $this->request->param('type') ?? 1;
        //Log::write($paytype, 'notice');
        if ($type_data == 1) {
            $pay = Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            Log::write($pay, 'error');
            $data = $pay->verify();
        } else {

            $data = $this->request->param();
        }
        //Log::write($data, 'error');
        Db::startTrans();
        try {
            $payamount = $paytype == 'wechat' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            //Log::write($out_trade_no, 'error');
            $order = Order::where(["out_trade_no" => $out_trade_no, "status" => '0'])->find();
            //Log::write($order, 'error');
            $order->status = "1";
            if ($order["type_data"] == 0) {
                $order->status = "3";
            }
            $order->save();
            $time = time();
            $mycardModel = new Mycard();
            if (!empty($order["merchant_id"])) {
                $merchant = \app\common\model\Merchant::field("name")->where(["id" => $order["merchant_id"]])->find();
                $info = "您已在" . $merchant["name"] . "店铺" . date("Y-m-d H:i:s") . " 购买" . $order["name"] . " ，价格" . $order["actual_payment"] . "元。祝你行程愉快。";
            }
            if ($order["type_data"] > 0) {
                $mycardlogModel = new Mycardlog();
                $card_data = [
                    "order_id" => $order["id"],
                    "card_kabaw_id" => $order["card_kabaw_id"] ?? 0,
                    "name" => $order["name"],
                    "price" => $order["price"],
                    "illustrate" => $order["illustrate"],
                    "details" => $order["details"],
                    "member_id" => $order["member_id"],
                    "type_data" => $order["type_data"],
                    "write_number" => $mycardlogModel->write_number(10),
                    "createtime" => $time,
                ];
                $cardlog_data = [];
                $write_number = $mycardlogModel->write_number(10);
                if ($order["type_data"] == 1) {
                    //卡包
                    $info = "您已在平台" . date("Y-m-d H:i:s") . " 购买" . $order["name"] . " ，价格" . $order["actual_payment"] . "元。祝你行程愉快。";
                    $kabaw = Kabaw::get($order["card_kabaw_id"]);
                    $time = time();
                    if (!empty($kabaw)) {
                        $card_data["start_time"] = $time;
                        $card_data["end_time"] = strtotime("+" . $kabaw["fate"] . " days", $time);
                        $kabawtype = Kabawtype::where(["card_kabaw_id" => $kabaw["id"]])->select();//卡包洗车类型
                        if (!empty($kabawtype)) {
                            foreach ($kabawtype as $k => $v) {
                                $cardlog_data[$k] = [
                                    "card_type_name" => $v["card_type_name"],
                                    "card_type_id" => $v["card_type_id"],
                                    "number" => $v["number"],
                                    "residue" => $v["number"],
                                    "price" => $v["price"],
                                    "all_cost" => $v["all_cost"],
                                    "write_number" => $write_number,
                                    "highest_price" => $v["highest_price"],
                                ];
                            }
                        }
                    }
                }
                if ($order["type_data"] == 2) {
                    //商家卡券
                    $goods = Merchantgoods::get($order["card_kabaw_id"]);
                    if (!empty($goods)) {
                        $card_data["start_time"] = $goods["start_time"];
                        $card_data["end_time"] = $goods["end_time"];
                        $card_data["merchant_id"] = $goods["merchant_id"];
                        $cardlog_data[] = [
                            "card_type_name" => $goods["name"],
                            "card_type_id" => 0,
                            "number" => $goods["number"],
                            "residue" => $goods["number"],
                            "price" => $goods["price"],
                            "write_number" => $write_number,
                            "highest_price" => $goods["highest_price"],
                        ];
                    }
                }
                if (!empty($card_data)) {
                    $mycard_id = $mycardModel->insertGetId($card_data);
                    $mycardModel->getCode($mycard_id, 1);//生成二维码
                    if (!empty($cardlog_data)) {
                        foreach ($cardlog_data as &$v) {
                            $v["mycard_id"] = $mycard_id;
                        }
                        $mycardlogModel->allowField(true)->saveAll($cardlog_data);
                    }
                }
            } else {
                //普通商品
                $orderModel = new Order();
                //普通商品生成核销码
                $order_data["write_number"] = $orderModel->write_number(6);
                $mycardModel->getCode($order["id"], 0);//生成二维码
            }
            if (in_array($order["type_data"], [0, 2])) {
                $model = new Order();
                $res=$model->calculateCommission($order);
                /*$model=new \app\common\model\Regionservice();
                $model->money($res["merchant_money"], $res["merchant_id"],$res["momo"],1);*/
            }
            //给上级分销商分钱 start
            if($order["type_data"]==1){
                //卡包
                $model = new Order();
                $res=$model->agentCommission($order);
            }
            //给上级分销商分钱 end
            \app\common\model\Message::create([
                "title" => "购买成功",
                "member_ids" => $order["member_id"],
                "info" => $info,
                "createtime" => time(),
            ]);
            //新增 给用户发送模板消息 start
            $member=Member::find($order["member_id"]);
            //$member["wxopenid"]="onyHr51gVC3cRH8BqCBjp8Eb8JR8";
            if(!empty($member["wxopenid"])){
                $template_id="T2l7vsvGSY6a-3hMs2zVAbRCnsUP0_pAVlqPav0P6gw";
                if($order["type_data"]==1 || $order["type_data"]==2){
                    //卡包
                    $data=[
                        "thing3"=>[
                            "value"=>$order["name"],
                        ],
                        "amount4"=>[
                            "value"=>$order["price"],
                        ],
                        "time5"=>[
                            "value"=>date("Y-m-d H:i:s",time())
                        ],
                    ];
                    $mycard=Mycard::field("start_time,end_time")->where(["order_id"=>$order["id"]])->find();
                    if(!empty($mycard)){
                        $data["time5"]=[
                            "value"=>date("Y-m-d H:i:s",$mycard["start_time"])."~".date("Y-m-d H:i:s",$mycard["end_time"])
                        ];
                    }
                }
                if(empty($order["type_data"])){
                    $template_id="nKrtffukSy1Ov9SBf1HbF-81XvqiDkLoQYRXme3OFjY";
                    $data=[
                        "character_string2"=>[
                            "value"=>$order["order_no"],
                        ],//订单编号
                        "amount3"=>[
                            "value"=>$order["price"],
                        ],//订单金额
                        "thing5"=>[
                            "value"=>$merchant["name"]??"团洗",
                        ],//商户名称
                        "thing8"=>[
                            "value"=>$order["name"]
                        ],//产品名称
                        "time4"=>[
                            "value"=>date("Y-m-d H:i:s",time())
                        ],//支付时间
                    ];
                }
                //$order["id"]=286;
                $this->send_temp($template_id,$member["wxopenid"],$data,"my_pages/orderDetails/orderDetails?id=".$order["id"]);
            }
            //新增 给用户发送模板消息 end
            Db::commit();
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            Db::rollback();
        }
        if ($type_data == 1) {
            return $pay->success();
        }
    }

    /**
     * banner列表
     * */
    public function bannerList(){
        //$page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Banner::field("id,image")->order("weigh","desc")->select();
            //->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }
    /**
     * 问答列表
     * */
    public function questionList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Question::field("id,name")
            ->order("weigh","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }
    /**
     * 问答详情
     * */
    public function questionSee(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list = Question::field("id,name,content,createtime")
            ->where(["id"=>$this->request->param("id")])
            ->find();
        $this->success("成功", $list);
    }
    /**
     * 模板消息 发送
     * @param $touser
     * @param $arr
     */
    public function send_temp($template_id='T2l7vsvGSY6a-3hMs2zVAbRCnsUP0_pAVlqPav0P6gw',$openid='',$param,$pagepath="pages/index/index",$parkUrl='')
    {
        /*$template_id="T2l7vsvGSY6a-3hMs2zVAbRCnsUP0_pAVlqPav0P6gw";
        $openid="onyHr51gVC3cRH8BqCBjp8Eb8JR8";*/
        //小程序信息获取token
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $appid = "wx64d13e22fd555473";
        $secret = "8fa5215c227de9d52eda3c58a79e7a11";
        $url .= "?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $data = \fast\Http::get($url);
        $data=json_decode($data,true);
        if (isset($data['access_token'])) {
            $send_url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$data['access_token'];
            $template=[
                'touser'=>$openid,//openID
                'template_id'=>$template_id,//模版id
                'url'=>$parkUrl,
                "miniprogram"=>[
                    "appid"=>"wx8a376411ca7f6697",
                    "pagepath"=>$pagepath
                ],
                'topcolor'=>"#7B68EE",
                'data'=>$param
            ];//各个参数不明白的就去看文档，很详细。
            if(!empty($url)){
                unset($template["miniprogram"]);
            }
            Log::log("发送数据data:".json_encode($template));
            $send_data_decode = json_encode($template, true);
            $res_send =Http::post($send_url,$send_data_decode);
            Log::log("发送后data:".json_encode($res_send));
            //dump($res_send);die();
            return $res_send;
            return $res_send = $this->sendCmd($send_url, $send_data_decode);
        }
    }

    /*public function generatescheme(){
        // 获取token
        $id=$this->request->param("id");
        $type=$this->request->param("type");
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $appid = "wx8a376411ca7f6697";
        $secret = "bb1a1cd8f21aa1cbdd8852e0569be332";
        $url .= "?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $token = \fast\Http::get($url);
        $token=json_decode($token,true);
        $url="https://api.weixin.qq.com/wxa/generatescheme?access_token=".$token["access_token"];
        // 微信返回的信息
        $data = json_encode([
            "jump_wxa"=>[
                "path"=>"/pages/index/index",
                "query"=>"id=".$id."&type=".$type,
                "env_version"=>"trial"
            ],
        ], true);
        $returnData = json_decode(\fast\Http::post($url,$data));
        $this->success("",$returnData);
    }*/
    public function generatescheme(){
        // 获取token
        $id=$this->request->param("id");
        $type=$this->request->param("type");
        $token =getWxAccessToken();
        if(!isset($token["access_token"])){
            $token =getWxAccessToken();
        }
        if(isset($token["access_token"])){
            $url="https://api.weixin.qq.com/wxa/generatescheme?access_token=".$token["access_token"];
            // 微信返回的信息
            $data = json_encode([
                "access_token"=>$token["access_token"],
                "jump_wxa"=>[
                    "path"=>"pages/index/index",
                    "query"=>"id=".$id."&type=".$type,
                    "env_version"=>"trial"
                ],
            ], true);
            $returnData = json_decode(\fast\Http::post($url,$data));
            $this->success("",$returnData);
        }
    }
}
